// import { Message } from 'element-ui';
import NProgress from 'nprogress'; // progress bar
import router from './router';
import store from './store';

import 'nprogress/nprogress.css'; // progress bar style

import { getToken } from '@/utils/auth'; // get token from cookie

NProgress.configure({ showSpinner: false }); // NProgress Configuration 取消加载loading

const whiteList = ['/login']; //  白名单

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start();
  const hasToken = getToken();
  if (hasToken) {
    if (to.path === '/login') {
      NProgress.done();
      next();
    } else {
      // 后台权限 确定用户是否通过getinfo获得了权限角色
      const hasRoles = store.getters.roles && store.getters.roles.length > 0;
      if (hasRoles) {
        next();
      } else {
        try {
          // 获取用户角色
          const roles = await store.dispatch('user/getInfo');
          // 根据用户角色设置路由
          const accessRoutes = await store.dispatch('permission/generateRoutes', roles);
          // 将路由加入用户角色
          router.addRoutes(accessRoutes);
          next({ ...to, replace: true });
        } catch (err) {
          next(`/login?redirect=${to.path}`);
          NProgress.done();
        }
      }
    }
  } else if (whiteList.findIndex(item => item === to.path) !== -1) {
    next();
  } else {
    next(`/login?redirect=${to.path}`);
    NProgress.done();
  }
});
router.afterEach(() => {
  // finish progress bar
  NProgress.done();
});
